<?php

namespace helper;


use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\Exception\InvalidPathException;
use Endroid\QrCode\QrCode as Qr;
use think\Response;

class Qrcode
{

  /**
   * 创建二维码
   * @param $text
   * @param array $options
   * @return string
   * @throws InvalidPathException
   */
  static private function create($text, $options = [])
  {
    $text   = urldecode($text);
    $config = [
        'label' => '',
        'size' => 430,
        'margin' => 10,
        'fore_ground_color' => ['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0],
        'back_ground_color' => ['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0],
        'logo_path' => '',
        'logo_width' => 100,
        'logo_height' => 100
    ];
    if (!empty($options)) $config = array_merge($config, $options);
    $qrCode = new Qr();
    $qrCode->setEncoding('UTF-8');
    $qrCode->setText($text);
    $qrCode->setLabel($config['label']);
    $qrCode->setSize($config['size']);
    $qrCode->setMargin($config['margin']);
    $qrCode->setForegroundColor($config['fore_ground_color']);
    $qrCode->setBackgroundColor($config['back_ground_color']);
    //$qrCode->setErrorCorrectionLevel('low');
    if (!empty($config['logo'])) {
      $qrCode->setLogoPath(app()->getRootPath() . 'public/' . $config['logo_path']);
      $qrCode->setLogoSize($config['logo_width'], $config['logo_height']);
      $qrCode->setRoundBlockSize(true);
    }
    return $qrCode;
  }

  /**
   * 创建二维码图片
   * @param $text
   * @param array $options
   * @return Response
   * @throws InvalidPathException
   */
  static public function img($text, $options = [])
  {
    $qrCode = self::create($text, $options);
    header('Content-Type: ' . $qrCode->getContentType());
    $response = response($qrCode->writeString(), 200, ['Content-Type' => $qrCode->getContentType()]);
    $response->contentType($qrCode->getContentType());
    return $response;
  }

  /**
   * 获取二维码base64数据
   * @param $text
   * @param $options
   * @return Response
   * @throws InvalidPathException
   */
  static public function base64($text, $options = [])
  {
    $qrCode = self::create($text, $options);
    return $qrCode->writeDataUri();
  }

  /**
   * 二维码保存本地
   * @param $text
   * @param $path
   * @param $options
   * @return mixed
   * @throws InvalidPathException
   */
  static public function save($text, $path, $options = [])
  {
    $qrCode = self::create($text, $options);
    $qrCode->writeFile(app()->getRootPath() . 'public/' . $path);
    return $path;
  }

}